package com.yuandengta.yomall.search.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yuandengta.common.to.es.SkuEsModel;
import com.yuandengta.common.utils.R;
import com.yuandengta.yomall.search.config.ElasticSearchConfig;
import com.yuandengta.yomall.search.constant.EsConstant;
import com.yuandengta.yomall.search.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /*商品上架*/
    @Override
    public boolean productUp(List<SkuEsModel> skuEsModelList) throws IOException {
        // 给 es 中建立索引，并建立好映射关系
        // ES批量保存
        BulkRequest bulkRequest = new BulkRequest();
        skuEsModelList.forEach(skuEsModel -> {
            // 指定索引
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            // 指定索引id
            indexRequest.id(skuEsModel.getSkuId().toString());

            ObjectMapper objectMapper = new ObjectMapper();
            String jsonString = null;
            try {
                jsonString = objectMapper.writeValueAsString(skuEsModel);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            // 设置数据
            indexRequest.source(jsonString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        });

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);

        // TODO 处理批量保存错误
        // true 有错误，false 没有错误
        boolean b = bulk.hasFailures();
        // 记录日志
        List<String> collect = Arrays.stream(bulk.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList());
        log.info("商品上架：{}", collect);

        return b;
    }

    /**
     * 商品下架
     */

    public boolean productDown1(List<SkuEsModel> skuEsModelList) {
        // 给 es 中建立索引，并建立好映射关系
        // ES批量删除
        skuEsModelList.forEach(skuEsModel -> {
            // 指定索引
            DeleteRequest deleteRequest = new DeleteRequest(EsConstant.PRODUCT_INDEX, skuEsModel.getSkuId().toString());
            try {
                restHighLevelClient.delete(deleteRequest, ElasticSearchConfig.COMMON_OPTIONS);
            } catch (IOException e) {
                throw new ElasticsearchException("删除索引 {" + EsConstant.PRODUCT_INDEX + "} 数据id {" + skuEsModel.getSkuId() + "} 失败");
            }
        });

        return true;
    }

    /**
     * 商品下架
     */
    @Override
    public boolean productDown(List<SkuEsModel> skuEsModelList) throws IOException {
        // 给 es 中建立索引，并建立好映射关系
        // ES批量删除
        BulkRequest bulkRequest = new BulkRequest();
        skuEsModelList.forEach(skuEsModel -> {
            // 指定索引
            DeleteRequest deleteRequest = new DeleteRequest(EsConstant.PRODUCT_INDEX);
            // 指定索引id
            deleteRequest.id(skuEsModel.getSkuId().toString());

            bulkRequest.add(deleteRequest);
            /*可以这样写*/
//            bulkRequest.add(new DeleteRequest(EsConstant.PRODUCT_INDEX,skuEsModel.getSkuId().toString()));
        });

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);

        // TODO 处理批量删除错误
        // true 有错误，false 没有错误
        boolean b = bulk.hasFailures();
        // 记录日志
        List<String> collect = Arrays.stream(bulk.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList());
        log.info("商品下架：{}", collect);

        return b;
    }

    /**
     * 简单的搜索功能
     *
     * @param keyword
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public R search(String keyword, Integer pageNum, Integer pageSize) throws IOException {
        SearchRequest request = new SearchRequest(EsConstant.PRODUCT_INDEX);
        SearchSourceBuilder builder = new SearchSourceBuilder();
//        builder.query(QueryBuilders.matchAllQuery());//无条件查询，默认每页5条记录

        builder.query(QueryBuilders.wrapperQuery(keyword));

        builder.from(pageNum).size(pageSize);//分页查询
        request.source(builder);
        SearchResponse response = restHighLevelClient.search(request,
                RequestOptions.DEFAULT);

        Iterator<SearchHit> hits = response.getHits().iterator();
        while (hits.hasNext()) {
            System.out.println(hits.next().getSourceAsString());//当然，因为输出的
//            为json格式数据，如果有需要我们可以转换为对象
        }
        restHighLevelClient.close();

        return null;
    }

    /***
     * 综合搜索、筛选、排序
     * @param keyword
     * @param brandId
     * @param productCategoryId
     * @param pageNum
     * @param pageSize
     * @param sort
     * @return
     *
     * 需要多条件查询 和 分页 查询
     */
    @Override
    public R search(String keyword, Long brandId, Long productCategoryId, Integer pageNum, Integer pageSize, Integer sort) {
        return null;
    }
}
